<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body v-dialogDrag width="90%">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"
             label-width="98px">
      <el-form-item label="工程名称" prop="gongchengName">
        <el-input v-model="queryParams.gongchengName" placeholder="请输入工程名称"
                  clearable @keyup.enter.native="getList"/>
      </el-form-item>
      <el-form-item label="产品编码" prop="goodsCode">
        <el-input v-model="queryParams.goodsCode" placeholder="请输入产品编码"
                  clearable @keyup.enter.native="getList"/>
      </el-form-item>
      <el-form-item label="产品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入产品名称"
                  clearable @keyup.enter.native="getList"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-form ref="form" :model="form" :rules="rules">
      <div v-if="selectedRows.length > 0">
      <span>已勾选数量合计: {{selectedRows.reduce((acc, row) => acc + row.orderCount, 0)}}</span>
    </div>
      <el-table :data="columns" @sort-change="handleSortChange" ref="dragTable" row-key="id" v-loading="loading" :row-class-name="tableRowClassName":summary-method="totalOutYear"
      show-summary @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="30" />
        <el-table-column align="center" label="序号" type="index" width="50">
          <template slot-scope="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable label="订单编号" align="center" prop="projectNo"/>
        <el-table-column sortable label="产品编码" align="center" prop="goodsCode"/>
        <el-table-column sortable label="工程名称" align="center" prop="gongchengName" show-overflow-tooltip/>
<!--        <el-table-column sortable align="center" label="客户名称" prop="order.companyName"/>-->
<!--        <el-table-column sortable align="center" label="业务员" prop="order.salesmanName"/>-->
        <el-table-column sortable label="需求日期" align="center" prop="deliveryTime" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.deliveryTime,'{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable align="center" label="产品名称" prop="goodsName"  show-overflow-tooltip/>
        <el-table-column sortable align="center" label="产品型号" prop="goodModel"/>
        <!--<el-table-column sortable align="center" label="订单单价" prop="goodsUnitPrice"/>-->
        <el-table-column align="center" label="订单数量" prop="orderCount"/>
        <el-table-column align="center" label="库存总量" prop="stockCount"/>
        <el-table-column align="center" label="可用数量" prop="remainderCount"/>

        <el-table-column align="center" label="锁定数量" prop="lockCount" width="150">
          <template slot-scope="scope">
            <el-input-number v-if="scope.row.orderCount >= scope.row.remainderCount" size="mini"
                             v-model="scope.row.lockCount" :min="0" :max="scope.row.remainderCount" @change="lockCountChange(scope.row)"></el-input-number>
            <el-input-number v-if="scope.row.orderCount < scope.row.remainderCount" size="mini"
                             v-model="scope.row.lockCount" :min="0" :max="scope.row.orderCount" @change="lockCountChange(scope.row)"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column align="center" label="请购数量" prop="pleaseBuyCount" width="150">
          <template slot-scope="scope">
            <el-input-number   size="mini" v-model="scope.row.pleaseBuyCount"  :min="0" :max="scope.row.orderCount"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip/>
      </el-table>
    </el-form>
    <div class="dialog-footer" slot="footer">

      <el-button type="primary" @click="submitBuyForm">发起请购到生产部</el-button>
      <el-button type="primary" @click="submitBuyToCaigouForm">发起请购到采购部</el-button>
      <el-button @click="cancel">取 消</el-button>
      <el-popconfirm :title="`确认要把锁定数量一键清零吗？`" @confirm="oneKeyReset()" style="margin-left: 10px;" >
        <el-button slot="reference"  type="danger" icon="el-icon-s-open">一键清0
        </el-button>
      </el-popconfirm>
    </div>
  </el-dialog>
</template>


<script>

import {addAction, deleteAction, getAction, accAdd, isEmpty} from '@/api/manage'

export default {
  name: "PleaseBuyFormGoodsByIds",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "订单产品1请购",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      ids: [],
      status: "",
      columns: [],
      total: 0,
      // 表单校验
      rules: {},
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        id: null,
        gongchengName: null,
        goodsName: null,
        goodsCode: null,
        orderByColumn: "sort",
        isAsc: "asc",
      },
      url: {
        listByOrderIds: '/goodsSale/goodsSale/listByOrderIds/',
        pleaseBuyForMultiOrders: '/goodsSaledo/goodsSaledo/pleaseBuyForMultiOrders',
        pleaseBuyForMultiOrdersToCaigou: '/goodsSaledo/goodsSaledo/pleaseBuyForMultiOrdersToCaigou',
      },
      selectedRows: [], // 用于存储勾选的行数据
    };
  },
  created() {

  },
  methods: {
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    totalOutYear(param) {
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if ( column.property === "orderCount" || column.property === "pleaseBuyCount") {

          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev , curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        name: null,
        master: null,
      };
      this.resetForm("form");
    },

    /** 提交按钮 */
    submitBuyForm() {
      if(!this.checkData()){
        return;
      }
      let that = this;
      let arrays = that.columns;
      let count = 0;
      for (let i = 0; i < arrays.length; i++) {
        if (arrays[i].pleaseBuyCount === 0) {
          count++;
        }
      }
      if (count === arrays.length) {
        this.$message({
          message: '请购数量都为0，无需请购。',
          type: 'warning'
        });
        return;
      }

      // for (let i = 0; i < arrays.length; i++) {
      //   if (isEmpty(arrays[i].pleaseBuyCount)) {
      //     this.$message({
      //       message: '第'+(i+1)+'行，请购数量不能为空',
      //       type: 'warning'
      //     });
      //     return;
      //   }
      // }

      for (let i = 0; i < arrays.length; i++) {
        if (isEmpty(arrays[i].lockCount)) {
          this.$message({
            message: '第'+(i+1)+'行，锁定数量不能为空',
            type: 'warning'
          });
          return;
        }
      }



      that.$refs["form"].validate(valid => {
        if (valid) {
          const params = Object.assign({});
          let p ={};
          p.orderIds = this.ids.toString();
          params.projectId = this.queryParams.projectId;
          params.proStatus = this.queryParams.status;
          params.params = p;
          params.columns = that._data.columns;
          addAction(this.url.pleaseBuyForMultiOrders, params).then(response => {
            this.$modal.msgSuccess("请购成功");
            this.open = false;
            this.$emit('ok');
          });
        }
      });
    },
    submitBuyToCaigouForm() {
      if(!this.checkData()){
        return;
      }
      let that = this;
      let arrays = that.columns;
      let count = 0;
      for (let i = 0; i < arrays.length; i++) {
        if (arrays[i].pleaseBuyCount === 0) {
          count++;
        }
      }
      if (count === arrays.length) {
        this.$message({
          message: '请购数量都为0，无需请购。',
          type: 'warning'
        });
        return;
      }
      that.$refs["form"].validate(valid => {
        if (valid) {
          const params = Object.assign({});
          let p ={};
          p.orderIds = this.ids.toString();
          params.projectId = this.queryParams.projectId;
          params.proStatus = this.queryParams.status;
          params.params = p;
          params.columns = that._data.columns;
          addAction(this.url.pleaseBuyForMultiOrdersToCaigou, params).then(response => {
            this.$modal.msgSuccess("请购成功");
            this.open = false;
            this.$emit('ok');
          });
        }
      });
    },
    tableRowClassName({row, rowIndex}) {
    },
    resetQuery() {
      this.queryParams.params = {}
        this.resetForm("queryForm");
        this.handleQuery();
    },
    handlePleaseByIds(ids) {
      this.ids = ids;
      this.reset();
      this.open = true;
      this.getList();
    },

    getList() {
      const ids = this.ids;
      this.loading = true;

      this.queryParams.ids= ids.toString();
      getAction(this.url.listByOrderIds, this.queryParams).then(response => {
        this.columns = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    checkData(){
      const items =this.columns;
      let flag = true;
      const groupBy = (array, key) => {
        return array.reduce((result, currentItem) => {
          // 使用 key 函数提取分组键，如果是字符串属性可以直接使用
          const groupKey = typeof key === 'function' ? key(currentItem) : currentItem[key];
          // 初始化分组数组（如果尚不存在）
          if (!result[groupKey]) {
            result[groupKey] = [];
          }
          // 将当前项添加到对应分组
          result[groupKey].push(currentItem);
          return result;
        }, {});
      };

      const groupedItems = groupBy(items, 'goodsId');
      console.log(groupedItems);

      Object.keys(groupedItems).forEach(category => {
        console.log(`Category: ${category}`);
        const remainderCount = groupedItems[category][0].remainderCount;
        const goodsName = groupedItems[category][0].goodsName;
        const goodsCode = groupedItems[category][0].goodsCode;
        let lockCountTotal = 0;
        groupedItems[category].forEach(item => {
          console.log(`- ${item.goodsCode}`);
          lockCountTotal+= item.lockCount;
        });

        if(lockCountTotal > remainderCount && remainderCount > 0){
          this.$modal.msgError(goodsCode+","+goodsName+",可用数量为："+remainderCount+",锁定数量:"+lockCountTotal+",超出范围，请重新填写！");
          flag =  false;
        }
      });
      return flag;

    },

    lockCountChange(row) {
      row.pleaseBuyCount = row.orderCount-row.lockCount;
    },
    oneKeyReset(){
      this.columns.forEach((item,index)=>{
        this.columns[index].lockCount=0;
        this.columns[index].pleaseBuyCount=this.columns[index].orderCount;
      });
    }


  }
};
</script>
<style>

</style>
